<?php
declare (strict_types=1);

namespace app\middleware;
/*
{ '100': 'Continue',
  '101': 'Switching Protocols',
  '102': 'Processing',
  '200': 'OK',
  '201': 'Created',
  '202': 'Accepted',
  '203': 'Non-Authoritative Information',
  '204': 'No Content',
  '205': 'Reset Content',
  '206': 'Partial Content',
  '207': 'Multi-Status',
  '208': 'Already Reported',
  '226': 'IM Used',
  '300': 'Multiple Choices',
  '301': 'Moved Permanently',
  '302': 'Found',
  '303': 'See Other',
  '304': 'Not Modified',
  '305': 'Use Proxy',
  '307': 'Temporary Redirect',
  '308': 'Permanent Redirect',
  '400': 'Bad Request',
  '401': 'Unauthorized',
  '402': 'Payment Required',
  '403': 'Forbidden',
  '404': 'Not Found',
  '405': 'Method Not Allowed',
  '406': 'Not Acceptable',
  '407': 'Proxy Authentication Required',
  '408': 'Request Timeout',
  '409': 'Conflict',
  '410': 'Gone',
  '411': 'Length Required',
  '412': 'Precondition Failed',
  '413': 'Payload Too Large',
  '414': 'URI Too Long',
  '415': 'Unsupported Media Type',
  '416': 'Range Not Satisfiable',
  '417': 'Expectation Failed',
  '418': 'I\'m a teapot',
  '421': 'Misdirected Request',
  '422': 'Unprocessable Entity',
  '423': 'Locked',
  '424': 'Failed Dependency',
  '425': 'Unordered Collection',
  '426': 'Upgrade Required',
  '428': 'Precondition Required',
  '429': 'Too Many Requests',
  '431': 'Request Header Fields Too Large',
  '451': 'Unavailable For Legal Reasons',
  '500': 'Internal Server Error',
  '501': 'Not Implemented',
  '502': 'Bad Gateway',
  '503': 'Service Unavailable',
  '504': 'Gateway Timeout',
  '505': 'HTTP Version Not Supported',
  '506': 'Variant Also Negotiates',
  '507': 'Insufficient Storage',
  '508': 'Loop Detected',
  '509': 'Bandwidth Limit Exceeded',
  '510': 'Not Extended',
  '511': 'Network Authentication Required' }
 * */

class Auth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */

    public function handle($request, \Closure $next)
    {
//        return json([
//            'code' => 0,
//            'msg' => 'Unauthorized',
//            'element' => '',
//            'data' => [],
//        ],401);
        //authorization
        $authorization = $request->header('authorization', '');
        $authorization = json_decode($authorization, true);
        $userid = isset($authorization['userid']) ? $authorization['userid'] : 0;
        $username = isset($authorization['username']) ? $authorization['username'] : '';
        $groupid = isset($authorization['groupid']) ? $authorization['groupid'] : 0;
        $auth = isset($authorization['auth']) ? $authorization['auth'] : '';
        $signature = isset($authorization['signature']) ? $authorization['signature'] : '';
        $rsa_token = isset($authorization['rsa_token']) ? $authorization['rsa_token'] : '';
//        if (!$userid || !$username || !$groupid || !$auth || !$signature) {
        if (!$userid || !$username || !$groupid || !$auth || !$rsa_token) {
            return json([
                'code' => 0,
                'msg' => 'Unauthorized',
                'element' => '',
                'data' => [],
            ], 401);
        }
//        if (!check_signature($signature, config('api.auth_key'))) {
//            return json([
//                'code' => 0,
//                'msg' => 'Signature error',
//                'element' => '',
//                'data' => [],
//            ], 401);
//        }
        $auth = decrypt($auth, config('api.auth_key'));
        if (!$auth) {
            return json([
                'code' => 0,
                'msg' => 'Unauthorized',
                'element' => '',
                'data' => [],
            ], 401);
        }
        //rsa解密
        if (!rsa_decode($rsa_token)) {
            return json([
                'code' => 0,
                'msg' => '数据验证失败rsa',
                'element' => '',
                'data' => [],
            ], 401);
        }
        list($_userid, $_username, $_groupid) = explode('|', $auth);
        if ($_userid == $userid && $_username == $username && $_groupid == $groupid) {
            //power
            /*
            $controller = $request->controller(true);
            $action = $request->action(true);

            if ($_groupid != 1 && !in_array($controller, ['home', 'index', 'menu', 'safe', 'upload'])) {
                $module = \Menu::get($controller);
                if ($module['is_auth'] && $module['power'][$action]['is_auth']) {
//                    file_put_contents('./1.txt',$controller.'/'.$action,FILE_APPEND);
                    $has_power = \think\facade\Db::name('access_back')->where(['userid' => $_userid, 'controller' => $controller, 'action' => $action])->value('itemid');
                    if (!$has_power) {
                        return json([
                            'code' => 0,
                            'msg' => 'Forbidden',
                            'element' => '',
                            'data' => [],
                        ], 403);
                    }
                }

            }
            */

            $request->userid = $_userid;
            $request->username = $_username;
            return $next($request);
        } else {
            return json([
                'code' => 0,
                'msg' => 'Unauthorized',
                'element' => '',
                'data' => [],
            ], 401);
        }
    }
}
